import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  BadRequestException,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { ApiResponse } from './response.dto';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();
    const message = exception.message || '服务器错误';

    // 获取异常响应对象
    const exceptionResponse = exception.getResponse();
    let errorMessage = message;
    let errorDetails: any = null;

    // 解析不同格式的异常响应
    if (typeof exceptionResponse === 'object' && exceptionResponse !== null) {
      if ('message' in exceptionResponse) {
        // 安全地处理message属性
        const messageProp = exceptionResponse.message;
        if (typeof messageProp === 'string') {
          errorMessage = messageProp;
        } else if (Array.isArray(messageProp) && messageProp.length > 0) {
          errorMessage = messageProp[0];
        }
      }

      // 提取验证错误详情
      if (
        'errors' in exceptionResponse &&
        Array.isArray(exceptionResponse.errors)
      ) {
        // 如果有验证错误数组，直接使用
        errorDetails = exceptionResponse.errors;
      } else if ('error' in exceptionResponse) {
        // 安全地处理error属性
        const errorProp = exceptionResponse.error;
        if (typeof errorProp === 'string') {
          errorDetails = errorProp;
        }
      }
    } else if (typeof exceptionResponse === 'string') {
      errorMessage = exceptionResponse;
    }

    // 对于参数验证失败的情况，提供更详细的信息
    if (
      status === HttpStatus.BAD_REQUEST &&
      exception instanceof BadRequestException
    ) {
      const apiResponse = new ApiResponse(
        status,
        '请求失败',
        undefined,
        errorMessage,
        request.originalUrl,
        errorDetails,
      );

      response.status(status).json(apiResponse);
      return;
    }

    const apiResponse = new ApiResponse(
      status,
      '请求失败',
      undefined,
      errorMessage,
      request.originalUrl,
      errorDetails,
    );

    response.status(status).json(apiResponse);
  }
}
